import json

from django.db.models import F

from myapp import models


def addHistoryData(userInfo, jobId):
    models.JobInfo.objects.filter(id=jobId).first()

    historyData = models.History.objects.filter(user_id=userInfo.id, job_id=jobId).first()
    if historyData:
        historyData.count = F('count') + 1
        historyData.save()
    else:
        models.History.objects.create(user_id=userInfo.id, job_id=jobId)

    return

def removeHistoryData(hisId):
    history = models.History.objects.filter(id=hisId).first()
    if history: history.delete()
    return


def getTableData(userInfo):
    historys = list(models.History.objects.filter(user=userInfo).order_by('-count'))

    def mapFn(item):
        print(item.job)
        item.job.salary = json.loads(item.job.salary)
        item.job.companyPeople = json.loads(item.job.companyPeople)
        item.job.workTag = json.loads(item.job.workTag)
        if item.job.companyTags != '无':
            item.job.companyTags = json.loads(item.job.companyTags)[0].split('，')
        if not item.job.pratice:
            item.job.salary = list(map(lambda x: str(int(x / 1000)), item.job.salary))
        else:
            item.job.salary = list(map(lambda x: str(x), item.job.salary))
        item.job.salary = '-'.join(item.job.salary)
        item.job.companyPeople = list(map(lambda x: str(x), item.job.companyPeople))
        item.job.companyPeople = '-'.join(item.job.companyPeople)
        return item

    return list(map(mapFn, historys))
